<?php

namespace catchAdmin\newsDeclare\controller;

use catchAdmin\basics\request\AddDataCreateRequest;
use catchAdmin\externalGoods\model\Goods as externalGoodsModel;
use catchAdmin\newsDeclare\model\NewsDeclare;
use catchAdmin\newsDeclare\model\NewsReview;
use catchAdmin\externalGoods\service\GoodsService as externalGoodsService;
use catchAdmin\system\model\Attachments;
use catchAdmin\system\model\Config;
use catcher\base\CatchRequest as Request;
use catcher\Code;
use QL\QueryList;
use think\Exception;
use think\facade\Db;
use think\Request as ThinkRequest;
use catcher\CatchAdmin;
use catcher\CatchAuth;
use catcher\CatchResponse;
use houniao\api\v1\Goods as GoodsApi;

class Review extends CatchAdmin
{
    public function __construct(NewsDeclare $newsDeclareModel,NewsReview $newsReviewModel)
    {
        $this->newsDeclareModel = $newsDeclareModel;
        $this->newsReviewModel = $newsReviewModel;
    }

    //列表
    public function index(CatchAuth $auth, Request $request)
    {
        $user = $auth->user();
        $tenant_id = $user['tenant_id'];

        return CatchResponse::paginate($this->newsDeclareModel->getList($tenant_id));
    }

    //列表
    public function counts(CatchAuth $auth, Request $request)
    {
        $type = $request->param('type','xw_review_num');

        $user = $auth->user();
        $tenant_id = $user['tenant_id'];
        $user_id = $user['id'];

        $where = [];
        $where['is_declare'] = 1;
        $where['type'] = $type == 'xw_review_num' ? '新闻奖' : '传播奖';
        if($tenant_id != 0 ){
            $where['tenant_id'] = $tenant_id;
        }

        $totalNum = $this->newsDeclareModel->where($where)->count();
        $self_counts = $this->newsReviewModel->alias('nr')
            ->leftJoin('db_news_declare nd','nd.id = nr.article_id')
            ->where([
            'nd.deleted_at'=>0,
            'nr.judge_id'=>$user_id,
            'nr.article_type'=>$where['type']
        ])->count();
        $max_counts = (new Config())
            ->where('key','review.' . $type)
            ->value('value');

        $result = [
            'totalNum'=>$totalNum,
            'self_counts'=>$self_counts,
            'max_counts'=>$max_counts
        ];
        return CatchResponse::success($result);
    }

    //列表
    public function detail($id,CatchAuth $auth, Request $request)
    {
        $user = $auth->user();
        $data = $this->newsDeclareModel->findBy($id);
        $data = $data->toArray();

        $data['attachments'] = !empty($data['attachments']) ? $data['attachments'] : [];
        $data['back_attachments'] = !empty($data['back_attachments']) ? $data['back_attachments'] : [];
        $data['attachments_cxxg'] = !empty($data['attachments_cxxg']) ? $data['attachments_cxxg'] : [];

        $data['is_rec'] = $this->newsReviewModel->where([
            'article_id'=>$id,
            'judge_id'=>$user['id']
        ])->value('id');

        foreach ($data['attachments_cxxg'] as &$value){
            $_d =  (new Attachments())->where('url',$value['file_fullurl'])->find()->toArray();
            $value['mime_type'] =$_d['mime_type'];
            $value['file_ext'] =$_d['file_ext'];
            $value['file_size'] =$_d['file_size'];
        }

        foreach ($data['attachments'] as &$value){
            $_d =  (new Attachments())->where('url',$value['file_fullurl'])->find()->toArray();
            $value['mime_type'] =$_d['mime_type'];
            $value['file_ext'] =$_d['file_ext'];
            $value['file_size'] =$_d['file_size'];
        }

        foreach ($data['back_attachments'] as &$value){
            $_d =  (new Attachments())->where('url',$value['file_fullurl'])->find()->toArray();
            $value['mime_type'] =$_d['mime_type'];
            $value['file_ext'] =$_d['file_ext'];
            $value['file_size'] =$_d['file_size'];
        }

        return CatchResponse::success($data);
    }

    //推荐
    public function recommend($id,CatchAuth $auth,Request $request){
        //$params = $request->post();
        $user = $auth->user();

        $max_counts = (new Config())->where('key','review.review_num')->value('value');
        $current_counts = $this->newsReviewModel->where([
            'judge_id'=>$user['id']
        ])->count();

        if($current_counts >= $max_counts){
            return CatchResponse::fail('超过最大评选数量');
        }

        $data = [
            'article_id'=>$id,
//            'judge_id'=>$user['tenant_id'],
            'judge_id'=>$user['id'],
            'tenant_id'=>$user['tenant_id']
        ];

        $this->newsReviewModel->storeBy($data);

        $newsDeclareModel =  $this->newsDeclareModel->find($id);
        $newsDeclareModel->recommend_counts =  ++$newsDeclareModel->recommend_counts;
        $newsDeclareModel->save();

        return CatchResponse::success();
    }


    //批量推荐
    public function batchRecommend(CatchAuth $auth,Request $request){
        $ids = $request->post('ids');
        $type = $request->post('type','xw_review_num');
        $user = $auth->user();

        $_type = $type == 'xw_review_num' ? '新闻奖' : '传播奖';
        $_type2 =  $type == 'xw_review_num' ? 'xw_px' : 'cb_px';

        //1判断是否提交过
        if(!empty($user['declare_info']) && array_key_exists($_type2,$user['declare_info'])){
            return CatchResponse::fail('已经评选，无法修改');
        }

        //$data = [];


        //2判断是否超过数量
        $max_counts = (new Config())->where('key','review.'  . $type)->value('value');
        $current_counts = $this->newsReviewModel->where(
            [
                ['article_type','=',$_type],
                ['judge_id','=',$user['id']],
                ['article_id','not in',$ids]
            ])->count();
        if((count($ids) + $current_counts) > $max_counts){
            return json([
                'code' => Code::PERMISSION_FORBIDDEN,
                'message'  => '超过最大评选数量',
            ]);
            //return CatchResponse::fail('超过最大评审数量');
        }


        Db::startTrans();
        try {
            foreach ($ids as $value){
                $newsDeclareModel =  $this->newsDeclareModel->find($value);

                $data = [
                    'article_type'=>$newsDeclareModel['type'],
                    'article_id'=>$value,
                    'judge_id'=>$user['id'],
                    'tenant_id'=>$user['tenant_id']
                ];

                //推荐前、判断是否已经推荐
                $find = $this->newsReviewModel->where($data)->find();
                if($find){
                    continue;
                }

                $this->newsReviewModel->createBy($data);
                $newsDeclareModel->recommend_counts =  ++$newsDeclareModel->recommend_counts;
                $newsDeclareModel->save();
            }

            Db::commit();
        }catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail('保存失败');
        }

        return CatchResponse::success();
    }

    //取消推荐
    public function unrecommend($id,CatchAuth $auth,Request $request){
        //$params = $request->post();
        $user = $auth->user();
        $tenant_id = $user['tenant_id'];
        $user_id = $user['id'];

        $model = $this->newsReviewModel;
        $model::destroy(function($query) use ($tenant_id,$id,$user_id){
            $query->where('judge_id', $user_id)->where('article_id', $id);
        },true);

        $newsDeclareModel =  $this->newsDeclareModel->find($id);
        $newsDeclareModel->recommend_counts =  --$newsDeclareModel->recommend_counts;
        $newsDeclareModel->save();


        return CatchResponse::success();
    }

    //批量取消推荐
    public function batchUnrecommend(CatchAuth $auth,Request $request){
        $ids = $request->post('ids');
        $type = $request->post('type','xw_review_num');


        $user = $auth->user();
        $tenant_id = $user['tenant_id'];
        $user_id = $user['id'];

        $_type = $type == 'xw_review_num' ? '新闻奖' : '传播奖';

        //1 判断是否已经评选
        $_type2 =  $type == 'xw_review_num' ? 'xw_px' : 'cb_px';
        if(!empty($user['declare_info']) && array_key_exists($_type2,$user['declare_info'])){
            return CatchResponse::fail('已经评选，无法修改');
        }

        foreach ($ids as $value){
            $model = $this->newsReviewModel;
            $id = $value;

            //推荐前、判断是否已经推荐
            $find = $this->newsReviewModel->where([
                'judge_id'=>$user_id,
                'article_id'=>$id
            ])->find();
            if(!$find){
                continue;
            }

            $model::destroy(function($query) use ($tenant_id,$id,$user_id){
                $query->where('judge_id', $user_id)->where('article_id', $id);
            },true);

            $newsDeclareModel =  $this->newsDeclareModel->find($id);
            $newsDeclareModel->recommend_counts =  --$newsDeclareModel->recommend_counts;
            $newsDeclareModel->save();
        }

        return CatchResponse::success();
    }

    public function create(CatchAuth $auth,Request $request)
    {
        $params = $request->post();
        $user = $auth->user();
        $params['tenant_id'] = $user['tenant_id'];
        $params['news_no'] = date('ymdHis') . mt_rand(1000,9999);
        if(array_key_exists('back_attachments',$params) && !empty($params['back_attachments'])){
            $params['is_declare'] = 1;
        }
        $id =  $this->newsDeclareModel->storeBy($params);
        $result = $this->newsDeclareModel->findBy($id);
        return CatchResponse::success($result,'新建成功');
    }

    public function update($id,CatchAuth $auth,Request $request)
    {
        $params = $request->post();
        unset($params['news_no'],$params['created_at']);
        $user = $auth->user();
        if(array_key_exists('back_attachments',$params) && !empty($params['back_attachments'])){
            $params['is_declare'] = 1;
        }
        $params['tenant_id'] = $user['tenant_id'];
        return CatchResponse::success($this->newsDeclareModel->updateBy($id,$params),'修改成功');
    }

    public function delete($id,CatchAuth $auth,Request $request){

        return CatchResponse::success($this->newsDeclareModel->deleteBy($id));
    }

    //是否包含区融媒体中心文章
    public function qurongtiNums(CatchAuth $auth,Request $request){
        $user_id = $auth->user()['id'];
        $nums =  $this->newsReviewModel
            ->alias('nr')
            ->leftJoin('db_news_declare nd','nr.article_id = nd.id' )
            ->leftJoin('users u','nd.creator_id = u.id')
            ->where('nr.judge_id',$user_id)
            ->whereLike('u.rec_unit','%融媒体中心%')
            ->count();

        return CatchResponse::success(['nums'=>$nums]);
    }

    public function reviewSubmit(CatchAuth $auth,Request $request){
        $type = $request->post('type');
        $user = $auth->user();

        $declare_info = $user['declare_info'];
        if(empty($declare_info)){
            $declare_info = [];
        }
        if($type  == 'xw'){
            $declare_info['xw_px'] = 1;
            $_type_name ='新闻奖';
            $_type_key = 'xw_review_num';
        }elseif($type == 'cb'){
            $declare_info['cb_px'] = 1;
            $_type_name ='传播奖';
            $_type_key = 'cb_review_num';
        }
        $user->declare_info = $declare_info;

        $max_counts = (new Config())->where('key','review.'  . $_type_key)->value('value');

        //判断数量是否满足
        $selectNum = $this->newsReviewModel->where([
            'article_type'=>$_type_name,
            'judge_id'=>$user['id']
        ])->count();

        if($max_counts != $selectNum){
            return json([
                'code'=>Code::PERMISSION_FORBIDDEN,
                'message'=>"评选数量仅{$selectNum}篇，需要选择{$max_counts}篇"
            ]);
//            return CatchResponse::fail("评选数量{$selectNum}，未达到{$max_counts}标准");
        }

        Db::startTrans();
        try {
            $user->save();
//            $this->newsDeclareModel::update([
//                'is_declare'=>1
//            ],['type'=>$_type_name,'creator_id'=>$user['id']]);

            Db::commit();
        }catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail('评选失败');
        }

        return CatchResponse::success();
    }

    public function getHtml(CatchAuth $auth,Request $request)
    {
//        return CatchResponse::success([22]);
        $ql = QueryList::getInstance();
        $ql  = $ql->get("https://www.workercn.cn/papers/grrb/2023/12/26/1/news-3.html");
  //      $ql = QueryList::html();
////        return CatchResponse::success(json_encode($ql->getHtml()));
//
        return CatchResponse::success(['html'=>$ql->getHtml()]);
//        echo $ql->getHtml();
//        return  $ql->getHtml();
    }
}